import React, { useEffect, useRef, useState, useMemo } from 'react';
import {
    notification,
    Spin,
    Modal,
    Form,
    Input,
    Cascader,
    Upload,
    message,
    AutoComplete,
    Select,
    Button,
    Table,
    InputNumber,
    Layout,
    Switch,
    TimePicker
} from 'antd'
import { InboxOutlined } from '@ant-design/icons';
import { baseURL } from 'src/service/interceptors'

import {
    cityGuess,
    addShop,
    searchplace,
    foodCategory
} from 'src/api/getData'

const { Content } = Layout;
const { Option } = Select;

function AddShop() {

    const [form] = Form.useForm();
    const [addform] = Form.useForm();
    const [fileList0, setFileList0] = useState([]);
    const [fileList1, setFileList1] = useState([]);
    const [fileList2, setFileList2] = useState([]);
    const [loading, setLoading] = useState(true);
    const [visible, setVisible] = useState(false);
    const [city, setCity] = useState();
    const [autoCompleteOption, setAutoCompleteOption] = useState([]);
    const [categorys, setCategorys] = useState();
    const [activities, setActivities] = useState([
        {
            icon_name: '减',
            name: '满减优惠',
            description: '满30减5，满60减8',
        }
    ])

    useEffect(() => {
        cityGuessAsync()
    }, [])

    useEffect(() => {
        if (!city) return
        setLoading(true)
        Promise.all([
            foodCategoryAsync(),
            querySearchAsync(city.name)
        ]).then(() => {
            setLoading(false)
        })
    }, [city])


    async function foodCategoryAsync() {
        try {
            const res = await foodCategory()
            const options = res.data.map(item => {
                const option = {
                    value: item.name,
                    label: item.name
                }
                const sub_categories = item.sub_categories
                if (sub_categories && sub_categories.length > 0) {
                    option.children = sub_categories.map(ele => {
                        return {
                            value: ele.name,
                            label: ele.name
                        }
                    })
                }
                return option
            })
            setCategorys(options)
        } catch (error) {

        }
    }

    async function cityGuessAsync() {
        try {
            const res = await cityGuess();
            setCity(res.data)
        } catch (error) {

        }
    }


    async function querySearchAsync(queryString) {
        if (queryString) {
            try {
                const res = await searchplace(city.id, queryString);
                const list = res.data.map(item => {
                    return {
                        ...item,
                        value: item.address
                    };
                })
                setAutoCompleteOption(list)
            } catch (err) {
                console.log(err)
            }
        }
    }

    const normFile = (e) => {
        console.log('Upload event:', e);
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }

    async function handleOk() {
        try {
            const values = await form.validateFields()
            const {
                description,
                image_path,
                name,
                catering_service_license_image,
                business_license_image,
                phone,
                promotion_info,
                float_delivery_fee,
                float_minimum_order_amount,
                is_premium,
                delivery_mode,
                is_new,
                bao,
                zhun,
                piao,
                category,
                address,
                rangeTime: [startTime, endTime]
            } = values;
            const { latitude, longitude } = city;
            setLoading(true)
            const params = {
                name,
                address,
                latitude,
                longitude,
                description,
                phone,
                promotion_info,
                float_delivery_fee,
                float_minimum_order_amount,
                is_premium,
                delivery_mode,
                bao,
                zhun,
                piao,
                new: is_new,
                startTime: startTime.format('HH:mm'),
                endTime: endTime.format('HH:mm'),
                image_path: image_path[0].response.data,
                business_license_image: business_license_image[0].response.data,
                catering_service_license_image: catering_service_license_image[0].response.data,
                activities,
                category: category.join('/')
            }
            const res = await addShop(params);
            if (res.code === 0) {
                message.success('添加成功')
            }
        } catch (error) {
            console.error(error)
        }
        setLoading(false)
    }

    function handleDelete(index) {
        const activitiesNew = [...activities]
        activitiesNew.splice(index, 1);
        setActivities(activitiesNew)
    }

    return <Layout>
        <Content>
            <Spin spinning={loading}>

                <Form
                    form={form}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                >
                    <Form.Item
                        name='name'
                        label="店铺名称"
                        rules={[{ required: true, message: '请输入!' }]}
                    >
                        <Input autoComplete="off" placeholder='请输入' />
                    </Form.Item>

                    <Form.Item
                        name='address'
                        label="详细地址"
                        rules={[{ required: true, message: '请输入!' }]}
                    >
                        <AutoComplete
                            options={autoCompleteOption}
                            onSearch={querySearchAsync}
                            placeholder="control mode"
                        />
                    </Form.Item>

                    <Form.Item noStyle>
                        当前城市：{city?.name}
                    </Form.Item>
                    <Form.Item
                        name='phone'
                        label="联系电话"
                        rules={[{ required: true, message: '请输入!' }]}
                    >
                        <Input autoComplete="off" placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        name='description'
                        label="店铺简介"
                        rules={[{ required: true, message: '请输入!' }]}
                    >
                        <Input autoComplete="off" placeholder='请输入' />
                    </Form.Item>

                    <Form.Item
                        name='promotion_info'
                        label="店铺标语"
                        rules={[{ required: true, message: '请输入!' }]}
                    >
                        <Input autoComplete="off" placeholder='请输入' />
                    </Form.Item>

                    <Form.Item
                        name='category'
                        label="店铺分类"
                        rules={[{ required: true, message: '请选择!' }]}
                    >
                        <Cascader options={categorys} placeholder="请选择" />
                    </Form.Item>

                    <Form.Item
                        label="店铺特点"
                    >
                        <Form.Item
                            name='is_premium'
                            label="品牌保证"
                            valuePropName="checked"
                        >
                            <Switch />
                        </Form.Item>
                        <Form.Item
                            name='delivery_mode'
                            label="蜂鸟专送"
                            valuePropName="checked"
                        >
                            <Switch />
                        </Form.Item>
                        <Form.Item
                            name='is_new'
                            label="新开店铺"
                            valuePropName="checked"
                        >
                            <Switch />
                        </Form.Item>
                        <Form.Item
                            name='bao'
                            label="外卖保"
                            valuePropName="checked"
                        >
                            <Switch />
                        </Form.Item>
                        <Form.Item
                            name='zhun'
                            label="准时达"
                            valuePropName="checked"
                        >
                            <Switch />
                        </Form.Item>
                        <Form.Item
                            name='piao'
                            label="开发票"
                            valuePropName="checked"
                        >
                            <Switch />
                        </Form.Item>
                    </Form.Item>
                    <Form.Item
                        name='float_delivery_fee'
                        label="配送费"
                        initialValue={5}
                        rules={[{ required: true, message: '请输入!' }]}
                    >
                        <InputNumber placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        name='float_minimum_order_amount'
                        label="起送价"
                        initialValue={20}
                        rules={[{ required: true, message: '请输入!' }]}
                    >
                        <InputNumber placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        name='rangeTime'
                        label="营业时间"
                        rules={[{ required: true, message: '请输入!' }]}
                    >
                        <TimePicker.RangePicker format='HH:mm' />
                    </Form.Item>

                    <Form.Item
                        label="上传店铺头像"
                        name="image_path"
                        valuePropName="fileList"
                        getValueFromEvent={normFile}
                        rules={[{ required: true, message: '请上传食品图片!' }]}
                    >
                        <Upload.Dragger
                            name='file'
                            action={`${baseURL}v1/addimg/shop`}
                            size={2} //2M
                            accept="image/jpeg,image/png"
                            multiple={false}
                            listType="picture"
                            showUploadList={false}
                            onChange={(info) => {
                                setFileList0([info.file]);
                                const status = info.file.status;
                                info.fileList.forEach(item => {
                                    item.thumbUrl = '';
                                });
                                if (status === 'uploading') {
                                    console.log(info.file, info.fileList);

                                }
                                if (status === "removed") {

                                    setFileList0([])
                                }
                                if (status === 'done') {
                                    console.log(`${info.file.name} file uploaded successfully.`);

                                }
                                if (status === 'error') {
                                    notification.error({
                                        message: "上传文件失败，请重试"
                                    });

                                }
                            }}
                            beforeUpload={(file) => {
                                return new Promise((resolve, reject) => {

                                    if (file.type !== 'image/jpeg') {
                                        notification.error({
                                            message: "导入格式不正确",
                                            duration: 5
                                        });
                                        return reject(false);
                                    }

                                    if (file.size / 1024 > 2 * 1024) {
                                        notification.error({
                                            message: "导入文件不能超过" + 2 + `M`,
                                            duration: 5
                                        });
                                        return reject(false);
                                    }

                                    return resolve(true);
                                });
                            }}
                            fileList={fileList0}
                        >
                            {
                                fileList0[0]?.response?.data ? <img src={`${baseURL}img/${fileList0[0].response.data}`} /> :
                                    <>
                                        <p className="ant-upload-drag-icon">
                                            <InboxOutlined />
                                        </p>
                                        <p className="ant-upload-text">Click or drag file to this area to upload</p>
                                        <p className="ant-upload-hint">Support for a single or bulk upload.</p>
                                    </>
                            }
                        </Upload.Dragger>
                    </Form.Item>
                    <Form.Item
                        label="上传营业执照"
                        name="business_license_image"
                        valuePropName="fileList"
                        getValueFromEvent={normFile}
                        rules={[{ required: true, message: '请上传食品图片!' }]}
                    >
                        <Upload.Dragger
                            name='file'
                            action={`${baseURL}v1/addimg/shop`}
                            size={2} //2 M
                            accept="image/jpeg,image/png"
                            multiple={false}
                            listType="picture"
                            showUploadList={false}
                            onChange={(info) => {
                                setFileList1([info.file]);
                                const status = info.file.status;
                                info.fileList.forEach(item => {
                                    item.thumbUrl = '';
                                });
                                if (status === 'uploading') {
                                    console.log(info.file, info.fileList);

                                }
                                if (status === "removed") {

                                    setFileList1([])
                                }
                                if (status === 'done') {
                                    console.log(`${info.file.name} file uploaded successfully.`);

                                }
                                if (status === 'error') {
                                    notification.error({
                                        message: "上传文件失败，请重试"
                                    });

                                }
                            }}
                            beforeUpload={(file) => {
                                return new Promise((resolve, reject) => {

                                    if (file.type !== 'image/jpeg') {
                                        notification.error({
                                            message: "导入格式不正确",
                                            duration: 5
                                        });
                                        return reject(false);
                                    }

                                    if (file.size / 1024 > 2 * 1024) {
                                        notification.error({
                                            message: "导入文件不能超过" + 2 + `M`,
                                            duration: 5
                                        });
                                        return reject(false);
                                    }

                                    return resolve(true);
                                });
                            }}
                            fileList={fileList1}
                        >
                            {
                                fileList1[0]?.response?.data ? <img src={`${baseURL}img/${fileList1[0].response.data}`} /> :
                                    <>
                                        <p className="ant-upload-drag-icon">
                                            <InboxOutlined />
                                        </p>
                                        <p className="ant-upload-text">Click or drag file to this area to upload</p>
                                        <p className="ant-upload-hint">Support for a single or bulk upload.</p>
                                    </>
                            }
                        </Upload.Dragger>
                    </Form.Item>

                    <Form.Item
                        label="上传餐饮服务许可证"
                        name="catering_service_license_image"
                        valuePropName="fileList"
                        getValueFromEvent={normFile}
                        rules={[{ required: true, message: '请上传食品图片!' }]}
                    >
                        <Upload.Dragger
                            name='file'
                            action={`${baseURL}v1/addimg/shop`}
                            size={2} //2 M
                            accept="image/jpeg,image/png"
                            multiple={false}
                            listType="picture"
                            showUploadList={false}
                            onChange={(info) => {
                                setFileList2([info.file]);
                                const status = info.file.status;
                                info.fileList.forEach(item => {
                                    item.thumbUrl = '';
                                });
                                if (status === 'uploading') {
                                    console.log(info.file, info.fileList);

                                }
                                if (status === "removed") {

                                    setFileList2([])
                                }
                                if (status === 'done') {
                                    console.log(`${info.file.name} file uploaded successfully.`);

                                }
                                if (status === 'error') {
                                    notification.error({
                                        message: "上传文件失败，请重试"
                                    });

                                }
                            }}
                            beforeUpload={(file) => {
                                return new Promise((resolve, reject) => {

                                    if (file.type !== 'image/jpeg') {
                                        notification.error({
                                            message: "导入格式不正确",
                                            duration: 5
                                        });
                                        return reject(false);
                                    }

                                    if (file.size / 1024 > 2 * 1024) {
                                        notification.error({
                                            message: "导入文件不能超过" + 2 + `M`,
                                            duration: 5
                                        });
                                        return reject(false);
                                    }

                                    return resolve(true);
                                });
                            }}
                            fileList={fileList2}
                        >
                            {
                                fileList2[0]?.response?.data ? <img src={`${baseURL}img/${fileList2[0].response.data}`} /> :
                                    <>
                                        <p className="ant-upload-drag-icon">
                                            <InboxOutlined />
                                        </p>
                                        <p className="ant-upload-text">Click or drag file to this area to upload</p>
                                        <p className="ant-upload-hint">Support for a single or bulk upload.</p>
                                    </>
                            }
                        </Upload.Dragger>
                    </Form.Item>

                    <Form.Item
                        name='activityValue'
                        label="优惠活动"
                        rules={[{ required: true, message: '请输入!' }]}
                        initialValue='满减优惠'
                    >
                        <Select
                            onChange={(e) => {
                                console.log(e, 'e')
                                setVisible(true)
                            }}
                        >
                            <Option value='满减优惠'>满减优惠</Option>
                            <Option value='优惠大酬宾'>优惠大酬宾</Option>
                            <Option value='新用户立减'>新用户立减</Option>
                            <Option value='进店领券'>进店领券</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item noStyle>
                        <Table
                            columns={[
                                {
                                    title: '活动标题',
                                    dataIndex: 'icon_name'
                                },
                                {
                                    title: '活动名称',
                                    dataIndex: 'name'
                                },
                                {
                                    title: '活动详情',
                                    dataIndex: 'description'
                                },
                                {
                                    title: '操作',
                                    dataIndex: 'action',
                                    render(text, record, index) {
                                        return <div>
                                            <Button
                                                onClick={() => handleDelete(index)}
                                                type="primary"
                                                danger
                                            >删除</Button>
                                        </div>
                                    }
                                },
                            ]}
                            dataSource={activities}
                            pagination={false}
                        />
                    </Form.Item>
                    <Form.Item noStyle>
                        <Button type="primary" onClick={handleOk}>立即创建</Button>
                    </Form.Item>
                </Form>
            </Spin>
        </Content>
        {
            visible && <Modal
                title="提示"
                visible
                onOk={async function () {
                    try {
                        const iconNameMap = new Map([
                            ['满减优惠', '减'],
                            ['优惠大酬宾', '特'],
                            ['新用户立减', '新'],
                            ['进店领券', '领']
                        ])
                        const activityValue = form.getFieldValue('activityValue')
                        const values = await addform.validateFields();
                        setActivities([...activities, {
                            icon_name: iconNameMap.get(activityValue),
                            name: activityValue,
                            ...values
                        }])
                        setVisible(false)
                    } catch (error) {

                    }
                }}
                onCancel={function () {
                    setVisible(false)
                }}
            >
                <Form
                    form={addform}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                >
                    <Form.Item
                        name='description'
                        label="请输入活动详情"
                        rules={[{ required: true, message: '请输入!' }]}
                    >
                        <Input autoComplete="off" placeholder='请输入' />
                    </Form.Item>
                </Form>
            </Modal>
        }
    </Layout>
}

export default AddShop